package com.itcast.codec.obj.server;

import com.itcast.codec.obj.server.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;

/**
 * @program: bio_tcp
 * @description:
 * @author: zhanghz001
 * @create: 2021-02-22 21:53
 **/
public class NettyObjectServer {
    public static void main(String[] args) {
        //    启动主监控线程.用于处理新的链接
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        //启动worker工作线程,用于处理已连接请求的的IO和事件
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //服务器启动类
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //绑定工作线程
            serverBootstrap.group(bossGroup, workerGroup);
            //,绑定链接的服务端的通道类型
            serverBootstrap.channel(NioServerSocketChannel.class);
            // ,绑定对应的pipeline,
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    //worker的线程处理器
                    socketChannel.pipeline()
                            .addLast(new ObjectDecoder(
                                    ClassResolvers.weakCachingResolver(
                                            this.getClass().getClassLoader()
                                    )
                            ))
                            .addLast(new ServerHandler())
                    ;
                }
            });
            
            //设置绑定端口
            ChannelFuture future = serverBootstrap.bind(8080).sync();
            System.out.println("服务器启动成功;");
            //等待服务器监听端口关闭
            future.channel().closeFuture().sync();
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //优雅关闭
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
